package com.qingluan.DataFormat;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.platform.comapi.map.a.l;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.qingluan.Database.MissionDataBase;
import com.qingluan.Database.ReceivedMissionDB;
import com.qingluan.Database.TempDataBase;
import com.qingluan.arguments.ARGUMENTS;
import com.qingluan.dd.InetTool.BitmapDownloader;
import com.qingluan.dd.InetTool.BitmapDownloader.CallBack;
import com.qingluan.widget.DragListViewAdapter;
import com.qingluan.widget.TimeHelper;

import android.app.DownloadManager.Request;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.Toast;

public class MissionTag {
	
	private ContentValues StringFormat = new ContentValues();
	private Bitmap image;
	private static String tag = "MissionTag";
	
	//data key area 
	public static  	String PICTURE = "picture_url";
	public static 	String MISSION_NAME = "mission_name";
	public static 	String MISSION_UP_EMAIL = "mission_up_email";
	public static 	String LATITUDE = "mission_latitude";
	public static 	String LONGITUDE = "mission_longitude";
	public static 	String MISSION_TAG = "mission_tag";
	public static 	String ATTENDEE = "attendee";
	public static 	String DESCRIBE = "mission_describe";
	public static 	String ACCESS_NUM = "mission_accept_num";
	public static 	String TIME_S = "begin_time";
	public static 	String TIME_C = "mission_continue";
	public static 	String MISS_OBJ_ID = "mission_object_id";
	public static 	String UP_NAME = "up_name";
	public static 	String PLACE_NAME = "mission_place_name";
	public static 	String NUM_PAR = "num";
	
	//context argu area
	private Context context_this_activityContext;
	
	

	public  MissionTag(Context context) {
		// TODO Auto-generated constructor stub
		this.context_this_activityContext = context;
	}
	
	public MissionTag (
			Bitmap image,
			String describe,
			String mission_name, 
			String tag,
			String time,
			String location
			){
		StringFormat.put("mission_name", mission_name);
		StringFormat.put("mission_describle", mission_name);
		StringFormat.put("mission_tag", tag);
		StringFormat.put("mission_time", tag);
		StringFormat.put("mission_location", location);
		this.image = image;
		
	}
	
	public MissionTag (
			String name,
			String email,
			String obj_id,
			String describe,
			String mission_name,
			String tag,
			String time,
			String latitude,
			String longitude,
			String picture_path
			){
		String [] Time = time.split("/");
		
		StringFormat.put(PICTURE, picture_path);
		StringFormat.put(MISSION_NAME, mission_name);
		StringFormat.put(MissionTag.UP_NAME, name);
		StringFormat.put(MissionTag.MISSION_UP_EMAIL, email);
		StringFormat.put(MissionTag.MISSION_TAG, tag);
		StringFormat.put(MissionTag.LATITUDE, latitude);
		StringFormat.put(MissionTag.LONGITUDE, longitude);
		StringFormat.put(MissionTag.MISS_OBJ_ID, obj_id);
		StringFormat.put(MissionTag.TIME_S, Time[0]);
		StringFormat.put(MissionTag.TIME_C, Time[1]);
		
		
		
	}
	
	public MissionTag(
			String name,
			String email,
			String obj_id,
			String uid,
			String time,
			String latitude,
			String longitude,
			String mission_name
			){
		
		String [] Time = time.split("/");
		
		StringFormat.put(MISSION_NAME, mission_name);
		StringFormat.put(MissionTag.UP_NAME, name);
		StringFormat.put(MissionTag.MISSION_UP_EMAIL, email);
		StringFormat.put(MissionTag.LATITUDE, latitude);
		StringFormat.put(MissionTag.LONGITUDE, longitude);
		StringFormat.put(MissionTag.MISS_OBJ_ID, obj_id);
		StringFormat.put(MissionTag.TIME_S, Time[0]);
		StringFormat.put(MissionTag.TIME_C, Time[1]);
		
		
	}
	
	/** 
	 * for para from web ..
	 * 
	 * 
	 * 
	 */
	public static String[] ProcessToAdapterByJson(Context context_this_activity,JSONObject json,final DragListViewAdapter adapter) throws JSONException{
		final String mission_id = json.getString("id");
		//mission info 
		String mission_name = json.getString("name");
		String mission_describe = json.getString("description");
		
		Log.d(tag, mission_describe);
		String mission_B_time = json.getString("begin_time");
		String mission_C_time = json.getString("continue_time");
		// up info 
		String mission_up_email = json.getString("up_email");
		String up_name = json.getString("up_name");
		String accept_num = json.getString("accept_num");
		//geo info 
		String placeString = json.getString("place_name");
		String lat  = json.getString("lat");
		String lon = json.getString("lon");
		
		JSONArray mission_attendee = json.getJSONArray("attendee");
		String mission_tag = "";
		JSONArray tag_json = json.getJSONArray("tag");
		
		for(int i= 0; i<tag_json.length();i++){
			mission_tag += tag_json.get(i) + " " ;
			Log.d("CACHE","Tag one :"+tag_json.get(i));
		}
		
		/*
		 * 
		 * insert info to local temple DB
		 */
		Log.d("CACHE", "Database loading ..................\n#####################");
		final TempDataBase TDB = new TempDataBase(context_this_activity);
		final MissionDataBase DB = new MissionDataBase(context_this_activity);
		Log.d("CACHE", "Database loading ..................\n#####################");
		DB.close();
		final ContentValues tempValues = new ContentValues();
		
		tempValues.put(TempDataBase.MISS_OBJ_ID, mission_id);
		tempValues.put(TempDataBase.MISSION_NAME, mission_name);
		tempValues.put(TempDataBase.MISSION_TAG, mission_tag);
		tempValues.put(TempDataBase.MISSION_UP_EMAIL, mission_up_email);
		tempValues.put(TempDataBase.UP_NAME, up_name);
		tempValues.put(TempDataBase.ATTENDEE, "");
		tempValues.put(TempDataBase.TIME_S,mission_B_time);
		tempValues.put(TempDataBase.TIME_C, mission_C_time);
		tempValues.put(TempDataBase.LATITUDE,lat);
		tempValues.put(TempDataBase.LONGITUDE, lon);
		tempValues.put(TempDataBase.PLACE_NAME, placeString);
		tempValues.put(TempDataBase.DESCRIBE, mission_describe);
		
		Log.d("mission place name :", placeString);
		
		Log.d("CACHE","DB key email :"+mission_up_email);
		String ifNullString = TDB.search(mission_B_time, TempDataBase.TIME_S, TempDataBase.MISS_OBJ_ID);
		if(ifNullString == null ){
			TDB.insertMission(tempValues);
		}else {
			Log.d("CACHE","if null :"+ifNullString);
		}
			
		
		
		// insert above info into list adapter.
		HashMap<String,String> oneCrow =  new HashMap<String,String>();
		oneCrow.put(MISSION_NAME, mission_name);
		oneCrow.put(MISS_OBJ_ID, mission_id);
		oneCrow.put(MISSION_TAG, mission_tag);
		oneCrow.put(DESCRIBE, mission_attendee+"\n"+mission_up_email+"\n"+mission_describe);
		
		//insert above geo info
		oneCrow.put(PLACE_NAME, placeString);
		oneCrow.put(LATITUDE, lat);
		oneCrow.put(LONGITUDE, lon);
		
		//time info 
		oneCrow.put(TIME_S,TimeHelper.paraTimeByLong(Long.parseLong(mission_B_time))+"~"+mission_C_time);
		
		
		oneCrow.put(UP_NAME, up_name);
		
		adapter.addData(oneCrow);
		
		//picture 
		String picture_info = json.getString("picture_path");
		//String picture_info_up = json.getString("up_picture_path");

		/*BitmapDownloader.Download(context_this_activity, picture_info_up, new CallBack(){

			@Override
			public void onDataGot(byte[] data) {
				// TODO Auto-generated method stub
				Bitmap upBitmap = BitmapFactory.decodeByteArray(data, 0, data.length); 
				adapter.addBitmapData(mission_id,upBitmap);
			}
			
		});
		*/
		return new String[]{ picture_info, mission_id,mission_up_email,mission_B_time};
	}
	
	
	
	
	
	/*
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 */
	public static String[] removeMission(final Context context_from,final String obj_id,String up_email ,final receiveSure sure) {
		AsyncHttpClient client = new AsyncHttpClient();
		RequestParams params = new RequestParams();
		JSONObject json_argument =new JSONObject ();
		try {
			json_argument.put("mission_id", obj_id);
			Log.d("CACHE","ARGU : missionid: "+obj_id);
			json_argument.put("mission_up_email", up_email);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		params.put(ARGUMENTS.REMOVE_MISSION, json_argument.toString());
		client.post(ARGUMENTS.REMOVE_MISSION_IP, params,new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String content) {
				// TODO Auto-generated method stub
				
				try {
					JSONObject json_info = new JSONObject(content);
					sure.Sure(json_info.getString("response"),obj_id);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
			}
			
			@Override
			public void onFailure(int statusCode, Throwable error,
					String content) {
				// TODO Auto-generated method stub
				Toast.makeText(context_from, error.toString(), Toast.LENGTH_SHORT).show();
			}
		});
		
		
		return null;
	}
	
	public static String [] archiveMission(final Context context_from, final String obj_id, String up_email,final receiveSure sure){
		AsyncHttpClient client = new AsyncHttpClient();
		RequestParams params = new RequestParams();
		JSONObject json_argument =new JSONObject ();
		try {
			json_argument.put("mission_id", obj_id);
			Log.d("CACHE","ARGU : missionid: "+obj_id);
			json_argument.put("mission_up_email", up_email);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		params.put(ARGUMENTS.POST_ARCHIVE, json_argument.toString());
		client.post(ARGUMENTS.ARCHIVE_MISSION_IP, params,new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String content) {
				// TODO Auto-generated method stub
				
				try {
					JSONObject json_info = new JSONObject(content);
					sure.Sure(json_info.getString("response"),obj_id);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
			}
			
			@Override
			public void onFailure(int statusCode, Throwable error,
					String content) {
				// TODO Auto-generated method stub
				Toast.makeText(context_from, error.toString(), Toast.LENGTH_SHORT).show();
			}
		});
		
		return null;
	}
	
	public interface  receiveSure {
		public void Sure(String info, String obj_id);
	}
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * for receive mission  
	 * 
	 * 
	 * 
	 * 
	 * 
	 */
	public static void ReceiveMission(Context context,String[] mission_info,final receiveMission callback){
		String mission_id = mission_info[0];
		String up_email = mission_info[1];
		AsyncHttpClient client = new AsyncHttpClient();
		RequestParams params = new RequestParams();
		JSONObject paraJson = new JSONObject();
		String resString = new TempDataBase(context).searchById(mission_id, MISSION_NAME);
		Log.d("CACHE", "pan ："+resString);
		try {
			paraJson.put("mission_id", mission_id);
			paraJson.put("join_email", up_email);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		params.put(ARGUMENTS.POST_RECEIVE,paraJson.toString());
		client.post(ARGUMENTS.RECEIVE_IP,params, new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String content) {
				// TODO Auto-generated method stub
				callback.sureMission(content);
			}
			
			@Override
			public void onFailure(int statusCode, Throwable error,
					String content) {
				// TODO Auto-generated method stub
				callback.errorHandler(content,error.toString());
			}
		});
	}
	
	
	
	public static String ParaJsonForSave(Context context,JSONObject infoJsonObject) throws JSONException {
		//mission info
		String mission_obj = infoJsonObject.getString("id");
		
		//joiner 
		JSONArray jsonArray =infoJsonObject.getJSONArray ("attendee");
		ArrayList<String> partners = new ArrayList<String>();
		String partner = "";
		for (int i = 0 ; i < jsonArray.length() ; i++){
			partners.add(i, jsonArray.getString(i));
			partner += " " + jsonArray.getString(i);
		}
		
		new TempDataBase(context).UpdateByOid(mission_obj, ATTENDEE, partner);
		ContentValues oneCrow = new TempDataBase(context).getMission(mission_obj);
		Log.d("CACHE","log ContentValue : "+oneCrow.toString());
		new MissionDataBase(context).UpdateByOid(mission_obj, ATTENDEE, partner);
		return mission_obj;
	}
	
	
	
	//base cal 
	public int count(){
		return this.StringFormat.size();
	}
	
	public boolean isEmpty(){
		if (this.StringFormat.size() ==0 ){
			return true;
		}
		return false;
	}
	
	public ContentValues getData(){
		if (StringFormat != null){
			return StringFormat;
		}else {
			return null;
		}
	
	}
	
	public Bitmap getPicture(){
		if (this.image != null){
			return this.image;
		}else {
			return null;
		}
	}
	
	public  String Get(String  key){
		String value = (String) this.StringFormat.get(key);
		return value;
	}
	
	public interface receiveMission{
		public void sureMission(String info);
		public void errorHandler(String info, String error);
	}
	
}
